import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetSocketAddress;

import java.net.SocketAddress;

/**
 * The type Datagram receive.
 */
public class DatagramReceive {

    private SocketAddress localAddr;

    private DatagramSocket dSender;

    /**
     * Instantiates a new Datagram receive.
     *
     * @throws Exception the exception
     */
    public DatagramReceive() throws Exception{

        localAddr=new InetSocketAddress("127.0.0.1",14000);

        dSender=new DatagramSocket(localAddr);

        //启动接收线程

        startRecvThread();

    }

    /**
     * Start recv thread.
     */
    public void startRecvThread(){

        new Thread(new Runnable(){

            @Override

            public void run() {

                try{

                    recvMsg();

                }catch(Exception e){

                    e.printStackTrace();

                }

            }}).start();

    }

    /**
     * Recv msg.
     *
     * @throws Exception the exception
     */
    public void recvMsg() throws Exception{

        System.out.println("接收线程启动");

        while(true){

            byte[] recvData=new byte[100];

            DatagramPacket recvPacket=new DatagramPacket(recvData,recvData.length);

            dSender.receive(recvPacket);

            NetJavaMsg recvMsg=new NetJavaMsg(recvPacket.getData());

            NetJavaRespMsg resp=new NetJavaRespMsg(recvMsg.getId(),(byte)0,System.currentTimeMillis());

            byte[] data=resp.toByte();

            DatagramPacket dp=new DatagramPacket(data,data.length,recvPacket.getSocketAddress());

            dSender.send(dp);

            System.out.println("接收端-已发送应答"+resp);

        }

    }

    /**
     * The entry point of application.
     *
     * @param args the input arguments
     * @throws Exception the exception
     */
    public static void main(String[] args) throws Exception{

        new DatagramReceive();

    }

}